package com.example.qrcodecamera;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.sql.Connection;

public class DBConfigActivity extends AppCompatActivity {

    private EditText etIp, etPort, etUsername, etPassword;
    private SharedPreferencesHelper spHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dbconfig);

        spHelper = new SharedPreferencesHelper(this);
        initViews();
        loadSavedConfig();
    }

    private void initViews() {
        etIp = findViewById(R.id.et_ip);
        etPort = findViewById(R.id.et_port);
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);

        Button btnTest = findViewById(R.id.btn_test_connect);
        Button btnSave = findViewById(R.id.btn_save);

        btnTest.setOnClickListener(v -> testConnection());
        btnSave.setOnClickListener(v -> saveConfig());
    }

    private void loadSavedConfig() {
        etIp.setText(spHelper.getIp());
        etPort.setText(spHelper.getPort());
        etUsername.setText(spHelper.getUsername());
        etPassword.setText(spHelper.getPassword());
    }

    private void testConnection() {
        new AsyncTask<Void, Void, Boolean>() {
            String errorMsg = "";

            @Override
            protected Boolean doInBackground(Void... voids) {
                try {
                    Connection conn = JDBCUtil.getNewConnection(
                            etIp.getText().toString(),
                            etPort.getText().toString(),
                            etUsername.getText().toString(),
                            etPassword.getText().toString()
                    );
                    conn.close();
                    return true;
                } catch (Exception e) {
                    errorMsg = e.getMessage();
                    return false;
                }
            }

            @Override
            protected void onPostExecute(Boolean success) {
                if (success) {
                    showToast("连接成功！");
                } else {
                    showToast("连接失败: " + errorMsg);
                }
            }
        }.execute();
    }

    private void saveConfig() {
        spHelper.saveConfig(
                etIp.getText().toString(),
                etPort.getText().toString(),
                etUsername.getText().toString(),
                etPassword.getText().toString()
        );
        showToast("配置已保存");
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}